package com.example.forecast;

import android.app.AlertDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.media.Image;
import android.os.Bundle;

import androidx.fragment.app.Fragment;


import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.example.forecast.DataBase.DataBaseManager;
import com.example.forecast.Juhe.HttpUtils;
import com.example.forecast.Juhe.JuheIndexBean;
import com.example.forecast.Juhe.JuheTempBean;
import com.example.forecast.Juhe.URLUtils;
import com.example.forecast.base.BaseFragment;
import com.google.gson.Gson;
import com.squareup.picasso.Picasso;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link CityWeatherFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class CityWeatherFragment extends BaseFragment implements View.OnClickListener{
    TextView tempTv,cityTv,conditionTv,windTv,tempRangeTv,dateTv,clothIndexTv,carIndexTv,coldIndexTv,sportIndexTv,raysIndexTv,airIndexTv;
    ImageView dayIv;
    LinearLayout futureLayout;
    ScrollView outLayout;
    JuheIndexBean.ResultBean.LifeBean lifeBean;     //指数信息
    String city;
    private SharedPreferences pref;
    private int bgNum;

    //    换壁纸的函数方法
    public void exchangeBg(){
        pref = getActivity().getSharedPreferences("bg_pref", Context.MODE_PRIVATE);
        bgNum = pref.getInt("bg", 2);
        switch (bgNum) {
            case 0:
                outLayout.setBackgroundResource(R.mipmap.bg);
                break;
            case 1:
                outLayout.setBackgroundResource(R.mipmap.bg2);
                break;
            case 2:
                outLayout.setBackgroundResource(R.mipmap.bg3);
                break;
        }
    }

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public CityWeatherFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment CityWeatherFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static CityWeatherFragment newInstance(String param1, String param2) {
        CityWeatherFragment fragment = new CityWeatherFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_city_weather, container, false);
        initView(view);
        exchangeBg();
//        可以通过activity传值获取到当前fragment加载的是哪个地方的天气情况
        Bundle bundle = getArguments();
        city = bundle.getString("city");
        String tempUrl = URLUtils.getTemp_url(city);
        String weatherUrl = URLUtils.getWeather_url();

//        调用父类获取数据的方法
        loadData(tempUrl);
        loadData(weatherUrl);

//        获取指数信息的网址
        String index_url = URLUtils.getIndex_url(city);
        loadIndexData(index_url);
        return view;
    }


//    网络获取指数信息的方法
    private void loadIndexData(final String index_url) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String json = HttpUtils.getJsonContent(index_url);
                JuheIndexBean JHIndexBean = new Gson().fromJson(json,JuheIndexBean.class);
                if (JHIndexBean.getResult()!=null){
                    lifeBean = JHIndexBean.getResult().getLife();
                }
            }
        }).start();
    }

    @Override
    public void onSuccess(String result) {
//        解析并展示数据
        parseShowData(result);
//        更新数据
        int i = DataBaseManager.updateInfoByCity(city, result);
        if (i<=0) {
//            更新数据库失败，说明没有这条城市信息，我们可以增加这条城市记录
            DataBaseManager.addCityInfo(city,result);
        }

    }
    @Override
    public void onError(Throwable ex, boolean isOnCallback) {
//        数据库当中查找上一次信息显示再Fragment当中
        String s = DataBaseManager.queryInfoByCity(city);
        if (!TextUtils.isEmpty(s)){
            parseShowData(s);
        }
    }

    private void parseShowData(String result) {
//        使用gson解析数据
        JuheTempBean juheTempBean = new Gson().fromJson(result, JuheTempBean.class);
        JuheTempBean.ResultBean JHResult = juheTempBean.getResult();
        /*WeatherBean weatherBean = new Gson().fromJson(result, WeatherBean.class);
          WeatherBean.ResultsBean resultsBean = weatherBean.getResults().get(0);*/

//        获取指数信息集合列表
        /*indexList = resultsBean.getIndex();*/

//        设置TextView
        dateTv.setText(JHResult.getFuture().get(0).getDate());
        cityTv.setText(JHResult.getCity());

//        获取今日天气情况
        /*WeatherBean.ResultsBean.WeatherDataBean TodayDataBean = resultsBean.getWeather_data().get(0);*/
        JuheTempBean.ResultBean.FutureBean JHTodayFuture = JHResult.getFuture().get(0);
        JuheTempBean.ResultBean.RealtimeBean JHRealtime = JHResult.getRealtime();

        windTv.setText(JHRealtime.getDirect()+JHRealtime.getPower());
        tempRangeTv.setText(JHTodayFuture.getTemperature());
        conditionTv.setText(JHRealtime.getInfo());

//        获取实时天气温度情况
        tempTv.setText(JHRealtime.getTemperature()+"℃");
        /*String[] split = TodayDataBean.getDate().split("：");
        String todayTemp = split[1].replace(")", "");
        tempTv.setText(todayTemp);*/

//        设置显示的天气情况图片
        switch (JHRealtime.getInfo()) {
            case "暴雪":
                dayIv.setImageResource(R.drawable.ic_baoxue);
                break;
            case "暴雨":
                dayIv.setImageResource(R.drawable.ic_baoyu);
                break;
            case "暴雨到大暴雨":
                dayIv.setImageResource(R.drawable.ic_baoyu_dabaoyu);
                break;
            case "大到暴雪":
                dayIv.setImageResource(R.drawable.ic_da_baoxue);
                break;
            case "大到暴雨":
                dayIv.setImageResource(R.drawable.ic_da_baoyu);
                break;
            case "大暴雨":
                dayIv.setImageResource(R.drawable.ic_dabaoyu);
                break;
            case "大暴雨到特大暴雨":
                dayIv.setImageResource(R.drawable.ic_dabaoyu_teda);
                break;
            case "大雪":
                dayIv.setImageResource(R.drawable.ic_daxue);
                break;
            case "大雨":
                dayIv.setImageResource(R.drawable.ic_dayu);
                break;
            case "冻雨":
                dayIv.setImageResource(R.drawable.ic_dongyu);
                break;
            case "多云":
                dayIv.setImageResource(R.drawable.ic_duoyun);
                break;
            case "浮尘":
                dayIv.setImageResource(R.drawable.ic_fuchen);
                break;
            case "雷阵雨":
                dayIv.setImageResource(R.drawable.ic_leizhenyu);
                break;
            case "雷阵雨伴有冰雹":
                dayIv.setImageResource(R.drawable.ic_leizhenyu_binbao);
                break;
            case "霾":
                dayIv.setImageResource(R.drawable.ic_mai);
                break;
            case "强沙尘暴":
                dayIv.setImageResource(R.drawable.ic_qiangshachenbao);
                break;
            case "晴":
                dayIv.setImageResource(R.drawable.ic_qing);
                break;
            case "沙尘暴":
                dayIv.setImageResource(R.drawable.ic_shachenbao);
                break;
            case "特大暴雨":
                dayIv.setImageResource(R.drawable.ic_tedabaoyu);
                break;
            case "雾":
                dayIv.setImageResource(R.drawable.ic_wu);
                break;
            case "小到中雪":
                dayIv.setImageResource(R.drawable.ic_xiao_zhongxue);
                break;
            case "小到中雨":
                dayIv.setImageResource(R.drawable.ic_xiao_zhongyu);
                break;
            case "小雪":
                dayIv.setImageResource(R.drawable.ic_xiaoxue);
                break;
            case "小雨":
                dayIv.setImageResource(R.drawable.ic_xiaoyu);
                break;
            case "扬沙":
                dayIv.setImageResource(R.drawable.ic_yangsha);
                break;
            case "阴":
                dayIv.setImageResource(R.drawable.ic_yin);
                break;
            case "雨夹雪":
                dayIv.setImageResource(R.drawable.ic_yujiaxue);
                break;
            case "阵雪":
                dayIv.setImageResource(R.drawable.ic_zhenxue);
                break;
            case "阵雨":
                dayIv.setImageResource(R.drawable.ic_zhenyu);
                break;
            case "中到大雪":
                dayIv.setImageResource(R.drawable.ic_zhong_daxue);
                break;
            case "中到大雨":
                dayIv.setImageResource(R.drawable.ic_zhong_dayu);
                break;
            case "中雪":
                dayIv.setImageResource(R.drawable.ic_zhongxue);
                break;
            case "中雨":
                dayIv.setImageResource(R.drawable.ic_zhongyu);
                break;

        }


//        获取未来三天的天气情况，加载到Layout当中
        List<JuheTempBean.ResultBean.FutureBean> futureList = JHResult.getFuture();
        /*List<WeatherBean.ResultsBean.WeatherDataBean> futureList = resultsBean.getWeather_data();*/
        futureList.remove(0);
        for (int i = 0; i < futureList.size(); i++) {
            View itemView = LayoutInflater.from(getActivity()).inflate(R.layout.item_main_center,null);  //放入布局中
            itemView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT));   //设置宽高
            futureLayout.addView(itemView);
            TextView idateTv = itemView.findViewById(R.id.item_center_tv_date);
            TextView iconTv = itemView.findViewById(R.id.item_center_tv_con);
            TextView windTv = itemView.findViewById(R.id.item_center_tv_wind);
            TextView itemprangeTv = itemView.findViewById(R.id.item_center_tv_temp);
            ImageView iIv = itemView.findViewById(R.id.item_center_iv);


//            获取对应的位置的天气情况
            JuheTempBean.ResultBean.FutureBean dataBean = futureList.get(i);
            idateTv.setText(dataBean.getDate());
            iconTv.setText(dataBean.getWeather());
            itemprangeTv.setText(dataBean.getTemperature());
            windTv.setText(dataBean.getDirect());
            switch (dataBean.getWeather()) {
                case "暴雪":
                    iIv.setImageResource(R.drawable.ic_baoxue);
                    break;
                case "暴雨":
                    iIv.setImageResource(R.drawable.ic_baoyu);
                    break;
                case "暴雨到大暴雨":
                    iIv.setImageResource(R.drawable.ic_baoyu_dabaoyu);
                    break;
                case "大到暴雪":
                    iIv.setImageResource(R.drawable.ic_da_baoxue);
                    break;
                case "大到暴雨":
                    iIv.setImageResource(R.drawable.ic_da_baoyu);
                    break;
                case "大暴雨":
                    iIv.setImageResource(R.drawable.ic_dabaoyu);
                    break;
                case "大暴雨到特大暴雨":
                    iIv.setImageResource(R.drawable.ic_dabaoyu_teda);
                    break;
                case "大雪":
                    iIv.setImageResource(R.drawable.ic_daxue);
                    break;
                case "大雨":
                    iIv.setImageResource(R.drawable.ic_dayu);
                    break;
                case "冻雨":
                    iIv.setImageResource(R.drawable.ic_dongyu);
                    break;
                case "多云":
                    iIv.setImageResource(R.drawable.ic_duoyun);
                    break;
                case "浮尘":
                    iIv.setImageResource(R.drawable.ic_fuchen);
                    break;
                case "雷阵雨":
                    iIv.setImageResource(R.drawable.ic_leizhenyu);
                    break;
                case "雷阵雨伴有冰雹":
                    iIv.setImageResource(R.drawable.ic_leizhenyu_binbao);
                    break;
                case "霾":
                    iIv.setImageResource(R.drawable.ic_mai);
                    break;
                case "强沙尘暴":
                    iIv.setImageResource(R.drawable.ic_qiangshachenbao);
                    break;
                case "晴":
                    iIv.setImageResource(R.drawable.ic_qing);
                    break;
                case "沙尘暴":
                    iIv.setImageResource(R.drawable.ic_shachenbao);
                    break;
                case "特大暴雨":
                    iIv.setImageResource(R.drawable.ic_tedabaoyu);
                    break;
                case "雾":
                    iIv.setImageResource(R.drawable.ic_wu);
                    break;
                case "小到中雪":
                    iIv.setImageResource(R.drawable.ic_xiao_zhongxue);
                    break;
                case "小到中雨":
                    iIv.setImageResource(R.drawable.ic_xiao_zhongyu);
                    break;
                case "小雪":
                    iIv.setImageResource(R.drawable.ic_xiaoxue);
                    break;
                case "小雨":
                    iIv.setImageResource(R.drawable.ic_xiaoyu);
                    break;
                case "扬沙":
                    iIv.setImageResource(R.drawable.ic_yangsha);
                    break;
                case "阴":
                    iIv.setImageResource(R.drawable.ic_yin);
                    break;
                case "雨夹雪":
                    iIv.setImageResource(R.drawable.ic_yujiaxue);
                    break;
                case "阵雪":
                    iIv.setImageResource(R.drawable.ic_zhenxue);
                    break;
                case "阵雨":
                    iIv.setImageResource(R.drawable.ic_zhenyu);
                    break;
                case "中到大雪":
                    iIv.setImageResource(R.drawable.ic_zhong_daxue);
                    break;
                case "中到大雨":
                    iIv.setImageResource(R.drawable.ic_zhong_dayu);
                    break;
                case "中雪":
                    iIv.setImageResource(R.drawable.ic_zhongxue);
                    break;
                case "中雨":
                    iIv.setImageResource(R.drawable.ic_zhongyu);
                    break;

            }


        }

    }




    private void initView(View view){
//        用于初始化控件操作
        tempTv = view.findViewById(R.id.frag_tv_currentTemp);
        cityTv = view.findViewById(R.id.frag_tv_city);
        conditionTv = view.findViewById(R.id.frag_tv_condition);
        windTv = view.findViewById(R.id.frag_tv_wind);
        tempRangeTv = view.findViewById(R.id.frag_tv_tempRange);
        dateTv = view.findViewById(R.id.frag_tv_date);
        clothIndexTv = view.findViewById(R.id.frag_index_tv_dress);
        carIndexTv = view.findViewById(R.id.frag_index_tv_WashCar);
        coldIndexTv = view.findViewById(R.id.frag_index_tv_cold);
        sportIndexTv = view.findViewById(R.id.frag_index_tv_sport);
        raysIndexTv = view.findViewById(R.id.frag_index_tv_rays);
        airIndexTv = view.findViewById(R.id.frag_index_tv_air);
        outLayout = view.findViewById(R.id.out_layout);
        dayIv = view.findViewById(R.id.frag_iv_today);
        futureLayout = view.findViewById(R.id.frag_center_layout);
        outLayout = view.findViewById(R.id.out_layout);

//        设置点击事件的监听
        clothIndexTv.setOnClickListener(this);
        carIndexTv.setOnClickListener(this);
        coldIndexTv.setOnClickListener(this);
        sportIndexTv.setOnClickListener(this);
        raysIndexTv.setOnClickListener(this);
        airIndexTv.setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        switch (v.getId()) {
            case R.id.frag_index_tv_dress:
                builder.setTitle("穿衣指数");
                String msg = "暂无信息";
                if (lifeBean!=null){
                    msg = lifeBean.getChuanyi().getV()+"\n"+lifeBean.getChuanyi().getDes();
                }
                builder.setMessage(msg);
                builder.setPositiveButton("确定",null);
                break;
            case R.id.frag_index_tv_WashCar:
                builder.setTitle("洗车指数");
                msg = "暂无信息";
                if (lifeBean!=null){
                    msg = lifeBean.getXiche().getV()+"\n"+lifeBean.getXiche().getDes();
                }
                builder.setMessage(msg);
                builder.setPositiveButton("确定",null);
                break;
            case R.id.frag_index_tv_cold:
                builder.setTitle("感冒指数");
                msg = "暂无信息";
                if (lifeBean!=null){
                    msg = lifeBean.getGanmao().getV()+"\n"+lifeBean.getGanmao().getDes();
                }
                builder.setMessage(msg);
                builder.setPositiveButton("确定",null);
                break;
            case R.id.frag_index_tv_sport:
                builder.setTitle("运动指数");
                msg = "暂无信息";
                if (lifeBean!=null){
                    msg = lifeBean.getYundong().getV()+"\n"+lifeBean.getYundong().getDes();
                }
                builder.setMessage(msg);
                builder.setPositiveButton("确定",null);
                break;
            case R.id.frag_index_tv_rays:
                builder.setTitle("紫外线指数");
                msg = "暂无信息";
                if (lifeBean!=null){
                    msg = lifeBean.getZiwaixian().getV()+"\n"+lifeBean.getZiwaixian().getDes();
                }
                builder.setMessage(msg);
                builder.setPositiveButton("确定",null);
                break;
            case R.id.frag_index_tv_air:
                builder.setTitle("空调指数");
                msg = "暂无信息";
                if (lifeBean!=null){
                    msg = lifeBean.getKongtiao().getV()+"\n"+lifeBean.getKongtiao().getDes();
                }
                builder.setMessage(msg);
                builder.setPositiveButton("确定",null);
                break;
        }
        builder.create().show();
    }
}